package com.xyxy.platform.openapi.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.util.Base64;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.service.trade.utils.ImgUtils;
import com.xyxy.platform.openapi.utils.ResultCodeEnum;

/**
 * 图片控制器
 * @author VIC
 */
//@RestController
//@RequestMapping("/app/v1/common/img")
public class ImgController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(ImgController.class);
	
	public ImgController(){
		
		//任务删除3小时前临时文件
		long clearImg = 1000 * 60 * 60 * 4;
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
		service.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				String tempImgPath = ImgUtils.getTempImgPath();
				if(StringUtils.isEmpty(tempImgPath)){
					logger.info("tempImgPath isEmpty");
					return ;
				}
				File file = new File(tempImgPath);
				if(!file.exists()){
					logger.info("tempImgPath not exists");
					return ;
				}
				if(!file.isDirectory()){
					logger.info("tempImgPath not directory");
					return ;
				}
				
				File[] subFiles = file.listFiles();
				if(subFiles == null){
					logger.info("tempImgPath subFiles isEmpty");
					return ;
				}
				long lastModified  =  0 ;
				long currTime = new Date().getTime();
				for(File f : subFiles){
					lastModified = f.lastModified();
					if(currTime - lastModified > 1000*60*60*1){
						f.delete();
					}
				}
				
			}
		}, 0 , clearImg , TimeUnit.MILLISECONDS);
		
		
	}

	/**
	 * 简介: 临时图片上传
	 * @author zhaowei
	 * @Date 2015年12月23日 下午3:00:13
	 * @version 1.0
	 *
	 * @return
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public  ResponseMessage<?>  tempUpload(){
		boolean success= false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		List<String> result = new ArrayList<String>();
		
		String[] imgs = request.getParameterValues("img");
		if(imgs != null && imgs.length > 0){
			boolean flag = true;
			for(String str : imgs){
				try {
					//Base64解码
					Base64  base64 = new Base64();
					byte[] b = base64.decodeFast(str);
					String imgFilePath = ImgUtils.getTempImgPath();
					String uuid  = "";
					
					for(int i=0;i<b.length;i++){
						if(b[i]<0){
							//调整异常数据
							b[i]+=256;
						}
					}
					
					uuid = UUID.randomUUID().toString();
					uuid = uuid.substring(0,8)+uuid.substring(9,13)+uuid.substring(14,18)+uuid.substring(19,23)+uuid.substring(24); 
					OutputStream out = new FileOutputStream(imgFilePath+"/"+uuid+".jpg");
					out.write(b);
					out.flush();
					out.close();
					
					result.add(uuid);
				} catch (Exception e) {
					e.printStackTrace();
					flag = false;
					break;
				}
				
			}
			
			if(flag){
				code = ResultCodeEnum.SUCCESS;
			}else{
				result.clear();
			}
		}
		
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	
	/**
	 * 简介: 会员临时图片上传,需要判断token  登录验证
	 * @author zhaowei
	 * @Date 2015年12月23日 下午3:00:13
	 * @version 1.0
	 *
	 * @return
	 */
	@RequestMapping(value = "/member/upload", method = RequestMethod.POST)
	public  ResponseMessage<?>  tempMemberUpload(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		List<String> result = new ArrayList<String>();
		
		String[] imgs = request.getParameterValues("img");
		if(imgs != null && imgs.length > 0){
			boolean flag = true;
			for(String str : imgs){
				try {
					//Base64解码
					Base64  base64 = new Base64();
					byte[] b = base64.decodeFast(str);
					String imgFilePath = ImgUtils.getTempImgPath();
					String uuid  = "";
					
					for(int i=0;i<b.length;i++){
						if(b[i]<0){
							//调整异常数据
							b[i]+=256;
						}
					}
					
					uuid = UUID.randomUUID().toString();
					uuid = uuid.substring(0,8)+uuid.substring(9,13)+uuid.substring(14,18)+uuid.substring(19,23)+uuid.substring(24);
					OutputStream out = new FileOutputStream(imgFilePath+"/"+uuid+".jpg");
					out.write(b);
					out.flush();
					out.close();
					
					result.add(uuid);
				} catch (Exception e) {
					e.printStackTrace();
					flag = false;
					break;
				}
				
			}
			
			if(flag){
				code = ResultCodeEnum.SUCCESS;
			}else{
				result.clear();
			}
		}
		
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
}
